package com.jy.api.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.api.form.QueryCategoryDataForm;
import com.jy.api.form.SaveCategoryDataForm;
import com.jy.framework.exception.MyException;
import com.jy.framework.sys.entity.SysDictDataEntity;
import com.jy.framework.sys.service.SysDictDataService;
import com.jy.framework.utils.PageUtils;
import com.jy.framework.utils.R;
import com.jy.web.diy.entity.AttributeEntity;
import com.jy.web.diy.entity.BaseInfoEntity;
import com.jy.web.diy.entity.CategoryEntity;
import com.jy.web.diy.service.BaseInfoService;
import com.jy.web.diy.service.CategoryService;
import com.jy.web.file.service.impl.File2Url;
import com.jy.web.qr.entity.ProductionQrEntity;
import com.jy.web.qr.service.ProductionQrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品二维码数据管理控制器
 *
 * @author fengshuonan
 * @Date 2018-07-27 22:35:25
 */
@Controller
@RequestMapping("anon/productionqr")
@Api(tags = "产品二维码数据管理")
public class ApiProductionQrController {

    @Autowired
    private BaseInfoService baseInfoService;
    @Autowired
    private ProductionQrService productionQrService;
    @Autowired
    private SysDictDataService sysDictDataService;

    @Autowired
    private CategoryService categoryService;
    /**
     * 产品二维码数据管理详情
     */
    @GetMapping(value = "/detail/{productionQrId}")
    @ResponseBody
    @ApiOperation("二维码数据详情")
    public R detail(@PathVariable("productionQrId") Integer productionQrId) {
        ProductionQrEntity productionqr = productionQrService.getById(productionQrId);
        List<BaseInfoEntity> baseInfoEntities = baseInfoService.getQrDatas(productionqr.getName());
        return R.ok().put("data", baseInfoEntities);
    }


    @RequestMapping("/attributes")
    @ResponseBody
    public R attributes(AttributeEntity entity) {
        List<Map<String, Object>> attributes = baseInfoService.getAttributeMaps(entity);
        CategoryEntity category = categoryService.getById(entity.getCategoryId());
        Map<String,Object> data=new HashMap<>(2);
        data.put("attributes",attributes);
        data.put("category",category);
        return R.ok().put("data", data);
    }
    /**
     * 保存
     */
    @PostMapping("/save")
    @ResponseBody
    public R save(@RequestBody BaseInfoEntity entity) {
        checkCategoryStatus(null,entity.getCategoryId());
        baseInfoService.saveBaseInfo(entity);
        return R.ok();
    }

    @GetMapping("/type/{dictType}")
    @ResponseBody
    public R selectDictDataByType(@PathVariable("dictType") String dictType){
        List<SysDictDataEntity> dictDataEntities = sysDictDataService.selectDictDataByType(dictType);
        return R.ok().put("data",dictDataEntities);
    }
    @GetMapping("/example/{categoryId}")
    @ResponseBody
    public R getExample(@PathVariable("categoryId") Long categoryId){

        CategoryEntity categoryEntity = categoryService.getById(categoryId);
        if (categoryEntity == null){
            throw new MyException("不存在 categoryId="+categoryId+" 的分类！");
        }

        AttributeEntity entity=new AttributeEntity();
        entity.setCategoryId(categoryId);
        List<Map<String, Object>> attributes = baseInfoService.getAttributeMaps(entity);
//   Map 中 value 为空时，会有空指针异常
//        Map<String, Object> attrExp = attributes.stream().peek(k->{
//            System.out.println((String)k.getOrDefault("defaultValue",""));
//            System.out.println((String)k.getOrDefault("code",""));
//        }).collect(Collectors.toMap(k -> (String)k.getOrDefault("code",""), v -> v.getOrDefault("defaultValue","")));

//   Map 中 value 为空时，不会有空指针异常
        Map<String, Object> attrExp = attributes.stream().peek(k->{
            System.out.println((String)k.getOrDefault("defaultValue",""));
            System.out.println((String)k.getOrDefault("code",""));
        }).collect(HashMap::new, (m, v) ->
                m.put(String.valueOf(v.get("code")), v.get("defaultValue")), HashMap::putAll);
//      save api
        HashMap<String, Object> re = new HashMap<>(3);
        re.put("category",categoryEntity.getCode());

        buildSave(categoryEntity, attrExp, re);

//      update api
        buildUpdate(attrExp, re);

//      delete api
        buildDelete(null, re);

//      info api
        buildInfo(categoryEntity, attrExp, re);

//      page api
        buildPage(categoryEntity, attrExp, re);


        return R.ok().put("data",re);
    }

    private void buildUpdate(Map<String, Object> attrExp, HashMap<String, Object> re) {
        Map<String,Object> update = new HashMap<>();
        update.put("id", R.genUUID());
        update.put("name",null);
        update.put("orderNum",null);
        update.put("remark",null);
        update.putAll(attrExp);

        //        String prettyStrRequest = JSONUtil.toJsonPrettyStr(saveCategoryDataForm);
        String prettyStrRequest = JSONObject.toJSONString(update, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
//      返回参数 example
        R ok = R.ok().put(R.DATA,R.genUUID());
//        String prettyStrResponse = JSONUtil.toJsonPrettyStr(ok);
        String prettyStrResponse = JSONObject.toJSONString(ok, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        buildResult(prettyStrRequest, prettyStrResponse, "update", re);
    }
    private void buildDelete(Map<String, Object> attrExp, HashMap<String, Object> re) {
//      返回参数 example
        R ok = R.ok().put(R.DATA,null);
//        String prettyStrResponse = JSONUtil.toJsonPrettyStr(ok);
        String prettyStrResponse = JSONObject.toJSONString(ok, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        buildResult(null, prettyStrResponse, "delete", re);
    }
    private void buildInfo(CategoryEntity categoryEntity, Map<String, Object> attrExp, HashMap<String, Object> re) {
        Map<String,Object> info = new HashMap<>();
        info.put("id",R.genUUID());
        info.put("categoryId",categoryEntity.getId());
        info.put("code",categoryEntity.getCode());
        info.put("categoryName",categoryEntity.getName());
        info.put("name",null);
        info.put("orderNum",null);
        info.put("remark",null);
        info.putAll(attrExp);
//      返回参数 example
        R ok = R.ok().put(R.DATA,info);
//        String prettyStrResponse = JSONUtil.toJsonPrettyStr(ok);
        String prettyStrResponse = JSONObject.toJSONString(ok, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        buildResult(null, prettyStrResponse, "info", re);
    }

    private void buildPage(CategoryEntity categoryEntity, Map<String, Object> attrExp, HashMap<String, Object> re) {
        QueryCategoryDataForm queryCategoryDataForm = new QueryCategoryDataForm();
        queryCategoryDataForm.setCategory(categoryEntity.getCode());
        queryCategoryDataForm.setCurrPage(1);
        queryCategoryDataForm.setPageSize(10);
//      请求参数 example
        String prettyStrRequest = JSONObject.toJSONString(queryCategoryDataForm, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
//      返回参数 example
        Page<Map> page = new Page<>();
        Map<String,Object> pageObj = new HashMap<>();
        pageObj.put("id",R.genUUID());
        pageObj.put("categoryId",categoryEntity.getId());
        pageObj.put("code",categoryEntity.getCode());
        pageObj.put("categoryName",categoryEntity.getName());
        pageObj.put("name",null);
        pageObj.put("orderNum",null);
        pageObj.put("remark",null);
        pageObj.putAll(attrExp);
        page.setRecords(Collections.singletonList(pageObj));
        PageUtils pageUtils = new PageUtils(page);
        R ok = R.ok().put(R.DATA,pageUtils);
        String prettyStrResponse = JSONObject.toJSONString(ok, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);

        buildResult(prettyStrRequest, prettyStrResponse, "page", re);
    }
    private void buildSave(CategoryEntity categoryEntity, Map<String, Object> attrExp, HashMap<String, Object> re) {
        SaveCategoryDataForm saveCategoryDataForm = new SaveCategoryDataForm();
        saveCategoryDataForm.setCategory(categoryEntity.getCode());

        Map<String,Object> save = new HashMap<>();
        save.put("name",null);
        save.put("orderNum",null);
        save.put("remark",null);
        save.putAll(attrExp);

        saveCategoryDataForm.setCategoryDataList(Collections.singletonList(save));
//      请求参数 example
//        String prettyStrRequest = JSONUtil.toJsonPrettyStr(saveCategoryDataForm);
        String prettyStrRequest = JSONObject.toJSONString(saveCategoryDataForm, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
//      返回参数 example
        R ok = R.ok().put(R.DATA,null);
//        String prettyStrResponse = JSONUtil.toJsonPrettyStr(ok);
        String prettyStrResponse = JSONObject.toJSONString(ok, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);

        buildResult(prettyStrRequest, prettyStrResponse, "save", re);
    }

    private void buildResult(String prettyStrRequest, String prettyStrResponse, String option, Map<String, Object> re) {
        Map<String,Object> save = new HashMap<>(2);
        save.put("request",prettyStrRequest);
        save.put("response",prettyStrResponse);
        re.put(option,save);
    }

    @PostMapping("/file/open/{categoryCode}")
    @ResponseBody
    public R uploadFile(@RequestParam("file") MultipartFile file,@PathVariable("categoryCode") String categoryCode) throws Exception {
        checkCategoryStatus(categoryCode, null);
        String s = File2Url.transferFile2Url(file, categoryCode);
        return R.ok().put(R.DATA, s);
    }

    private void checkCategoryStatus(String categoryCode, Long categoryId) {
        QueryWrapper<CategoryEntity> q=new QueryWrapper<>();
        q.lambda()
                .eq(StrUtil.isNotBlank(categoryCode),CategoryEntity::getCode,categoryCode)
                .eq(categoryId != null,CategoryEntity::getId,categoryId)
                .eq(CategoryEntity::getIsOpen,1)
        ;
        CategoryEntity one = categoryService.getOne(q);
        if (one == null){
            throw new MyException("禁止数据提交！");
        }
    }
}
